package cn.wowjoy.office.pm.view;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.PopupWindow;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.common.widget.AlphaManager;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.common.widget.MyToast;
import cn.wowjoy.office.common.widget.timepicker.BottomMenuPopupStock;
import cn.wowjoy.office.common.widget.timepicker.TimePickerView;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.response.StaffResponse;
import cn.wowjoy.office.databinding.ActivityPmReportDetailBinding;
import cn.wowjoy.office.homepage.MenuHelper;
import cn.wowjoy.office.pm.data.CardResponse;
import cn.wowjoy.office.pm.data.PmProjectResponse;
import cn.wowjoy.office.pm.data.PmReportDetailResponse;
import cn.wowjoy.office.pm.data.SubmitResponse;
import cn.wowjoy.office.pm.data.request.PmReportDetailSubmit;
import cn.wowjoy.office.pm.data.request.PmReportDtl;
import cn.wowjoy.office.pm.view.detail.ElectSafeActivity;
import cn.wowjoy.office.pm.view.detail.FunctionCheckActivity;
import cn.wowjoy.office.pm.view.detail.LookCheckActivity;
import cn.wowjoy.office.pm.view.detail.RemarkActivity;
import cn.wowjoy.office.pm.view.viewodel.PmReportDetailViewModel;
import cn.wowjoy.office.utils.DateUtils;
import cn.wowjoy.office.utils.MD5Util;
import cn.wowjoy.office.utils.MyTextWatcher;
import cn.wowjoy.office.utils.NetWorkUtils;
import cn.wowjoy.office.utils.PickerViewUtils;
import cn.wowjoy.office.utils.PreferenceManager;
import cn.wowjoy.office.utils.ToastUtil;
import cn.wowjoy.office.utils.dialog.DialogUtils;

public class PmReportDetailActivity extends PMBaseActivity<ActivityPmReportDetailBinding, PmReportDetailViewModel> implements View.OnClickListener {
    /**
     * 当前页面的状态
     */
    private int state;
    public static final int ELECT_SAFE = 100;
    public static final int LOOKCHECK = 200;
    public static final int FUNCTION = 300;
    public static final int REMARK = 101;
//    private String[] moudle = new String[]{"无","除颤器模版", "监护仪模版", "呼吸机模板", "高频电刀模板"
//            , "血液透析机模版", "婴儿培养箱模版", "史密斯输液泵模版", "费森尤斯输液泵模版"};
    //暂时就这两个模板
    private String[] moudle = new String[]{"无", "监护仪模版"};
    /**
     * 检测类型列表
     */
    private List<String> typeList = new ArrayList<>();
    private int typePosition;

    private TimePickerView pvTime;
    private OptionsPickerView typeOptionsPickerView;
    private PmReportDetailResponse detail;
    private PmReportDetailResponse localDetail;
//    /**
//     * 本页面的详情
//     */
//    PmReportDtl lookBean;
//    PmReportDtl elecBean;
//    PmReportDtl functionBean;

    private String elecId;
    private String lookId;
    private String functionId;

    private String cardId; //原本卡片的值
    private String replaceCardId;//扫码替换的值
    private MDialog waitDialog;
    private CardResponse res;

    /**
     * 明细详情的模块
     */
    private PmReportDetailSubmit submit;
    private PmReportDtl lookBack;
    private PmReportDtl elecBack;
    private PmReportDtl funtionBack;

    private StaffResponse userInfo;
    private BottomMenuPopupStock mMenuBottom;
    // 是否来自数据库 标识
    private boolean isLocalSave;

    private boolean isReplace = false;


    public static void launch(Context context, int state, String qrCode, PmReportDetailResponse detail,boolean isLocalSave) {
        Intent i = new Intent(context, PmReportDetailActivity.class);
        i.putExtra(Constants.PM_REPORT, state);
        i.putExtra("cardId", qrCode);
        i.putExtra("isLocalSave", isLocalSave);
        if (state == Constants.EDIT_REPORT || state == Constants.LOOK_REPORT)
            i.putExtra("detail", detail);
        context.startActivity(i);
    }

    @Override
    protected Class<PmReportDetailViewModel> getViewModel() {
        return PmReportDetailViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pm_report_detail;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);
        state = getIntent().getIntExtra(Constants.PM_REPORT, 1);
        userInfo = new Gson().fromJson(PreferenceManager.getInstance().getStuffInfo(), StaffResponse.class);
        cardId = getIntent().getStringExtra("cardId");
        replaceCardId = cardId;
        isLocalSave = getIntent().getBooleanExtra("isLocalSave",false);
        if (state == 2 || state == 3) {
            detail = (PmReportDetailResponse) getIntent().getSerializableExtra("detail");
        }
        typeList = Arrays.asList(moudle);
        submit = new PmReportDetailSubmit();
        initView();
        initData();
        initObserve();
//        new MyToast(PmReportDetailActivity.this).showinfo("该设备当前无法提交PM报告，请核实设备状态！");
    }

    private void initData() {

    }

    private void initObserve() {
        viewModel.pmProjectLook.observe(this, new Observer<LiveDataWrapper<PmProjectResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmProjectResponse> pmProjectResponseLiveDataWrapper) {
                switch (pmProjectResponseLiveDataWrapper.status) {
                    case LOADING:
                         DialogUtils.waitingDialog(PmReportDetailActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(PmReportDetailActivity.this);
                        if (null != pmProjectResponseLiveDataWrapper.data) {
//                            lookBack = pmProjectResponseLiveDataWrapper.data.getPrjInfo().getBasicInfo();
                            lookBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getAppMaiten());
                            lookBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getAppStatus());
                            LookCheckActivity.launch(PmReportDetailActivity.this, state, replaceCardId, res, lookBack);
                        }

                        break;
                    case ERROR:
                        DialogUtils.dismiss(PmReportDetailActivity.this);
                        handleException(pmProjectResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.pmProjectElec.observe(this, new Observer<LiveDataWrapper<PmProjectResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmProjectResponse> pmProjectResponseLiveDataWrapper) {
                switch (pmProjectResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(PmReportDetailActivity.this);
                        break;
                    case SUCCESS:
                           DialogUtils.dismiss(PmReportDetailActivity.this);
                        if (null != pmProjectResponseLiveDataWrapper.data) {
//                            elecBack = pmProjectResponseLiveDataWrapper.data.getPrjInfo().getBasicInfo();
                            elecBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getElePower());
                            elecBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getEleSimulator());
                            elecBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getEleCheckType());
                            ElectSafeActivity.launch(PmReportDetailActivity.this, state, replaceCardId, res, elecBack);
                        }

                        break;
                    case ERROR:
                           DialogUtils.dismiss(PmReportDetailActivity.this);
                        handleException(pmProjectResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.pmProjectFunction.observe(this, new Observer<LiveDataWrapper<PmProjectResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmProjectResponse> pmProjectResponseLiveDataWrapper) {
                switch (pmProjectResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(PmReportDetailActivity.this);
                        break;
                    case SUCCESS:
                           DialogUtils.dismiss(PmReportDetailActivity.this);
                        if (null != pmProjectResponseLiveDataWrapper.data) {
//                            funtionBack = pmProjectResponseLiveDataWrapper.data.getPrjInfo().getBasicInfo();
                            funtionBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getFunApp());
                            funtionBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getFunCheck());
                            funtionBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getFunOther());
                            funtionBack.addSelectBean(pmProjectResponseLiveDataWrapper.data.getPrjInfo().getFunSimulator());
                            FunctionCheckActivity.launch(PmReportDetailActivity.this, state, replaceCardId, res, funtionBack, binding.moduleFunction.getText().toString());
                        }

                        break;
                    case ERROR:
                           DialogUtils.dismiss(PmReportDetailActivity.this);
                        handleException(pmProjectResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });

        viewModel.submit.observe(this, new Observer<LiveDataWrapper<SubmitResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<SubmitResponse> pmReportDetailSubmitLiveDataWrapper) {
                switch (pmReportDetailSubmitLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(PmReportDetailActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(PmReportDetailActivity.this);
                        ToastUtil.toastImage(getApplication().getApplicationContext(), "提交成功", -1);
                        finish();
                        break;
                    case ERROR:
                        DialogUtils.dismiss(PmReportDetailActivity.this);
                        handleException(pmReportDetailSubmitLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.save.observe(this, new Observer<LiveDataWrapper<SubmitResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<SubmitResponse> pmReportDetailSubmitLiveDataWrapper) {
                switch (pmReportDetailSubmitLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(PmReportDetailActivity.this);
                        break;
                    case SUCCESS:
                           DialogUtils.dismiss(PmReportDetailActivity.this);
                        ToastUtil.toastImage(getApplication().getApplicationContext(), "提交成功", -1);
                        finish();
                        break;
                    case ERROR:
                           DialogUtils.dismiss(PmReportDetailActivity.this);
                        handleException(pmReportDetailSubmitLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.cardDetail.observe(this, new Observer<LiveDataWrapper<CardResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<CardResponse> cardResponseLiveDataWrapper) {
                switch (cardResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(PmReportDetailActivity.this);
                        break;
                    case SUCCESS:
                           DialogUtils.dismiss(PmReportDetailActivity.this);
                        if (null != cardResponseLiveDataWrapper.data) {
                            res = cardResponseLiveDataWrapper.data;
                            // 设置模板类型
                            if(!TextUtils.isEmpty(res.getPmFunModelName())){
                                binding.moduleFunction.setText(res.getPmFunModelName());
                                binding.changeModel.setVisibility(View.GONE);
                            }
                            if(binding.moduleFunction.getText().equals("无")){
                                binding.editFunctionCheck.setText("无");
                                binding.editFunctionCheck.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
                                binding.editFunctionCheck.setOnClickListener(null);
                                binding.editFunctionCheck.setTextColor(getResources().getColor(R.color.C_999999));
                                binding.proFunction.setText("");
                                binding.checkResultFunction.setText("");
                                //清除本身保存的数据
                                if(null != funtionBack){
                                    submit.removePmReportDtl(funtionBack);
                                }
                            }else{
                                if( null != funtionBack){
                                    if (state == 3 ){
                                        binding.editFunctionCheck.setText("点击查看");
                                    }else{
                                        binding.editFunctionCheck.setText("编辑");
                                    }
                                    binding.editFunctionCheck.setOnClickListener(PmReportDetailActivity.this);
                                }else{
                                    binding.editFunctionCheck.setText("添加");
                                    binding.editFunctionCheck.setCompoundDrawablesWithIntrinsicBounds(0,0,R.mipmap.go_01,0);
                                    binding.editFunctionCheck.setOnClickListener(PmReportDetailActivity.this);
                                    binding.editFunctionCheck.setTextColor(getResources().getColor(R.color.C_369FF1));
                                }
                            }
                            if(state == 1 || TextUtils.isEmpty(binding.taskRoom.getText())){ //如果是新增，科室取自卡片的数据
                                binding.taskRoom.setText(res.getDepartmentName());
                            }
                            binding.setModel(res);
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(PmReportDetailActivity.this);
//                        handleException(cardResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.localSave.observe(this, new Observer<LiveDataWrapper<PmReportDetailResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmReportDetailResponse> pmReportDetailResponseLiveDataWrapper) {
                switch (pmReportDetailResponseLiveDataWrapper.status) {
                    case LOADING:
                      DialogUtils.waitingDialog(PmReportDetailActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(PmReportDetailActivity.this);
                        ToastUtil.toastImage(PmReportDetailActivity.this,"保存成功",-1);
                        finish();
                        break;
                    case ERROR:
                        DialogUtils.dismiss(PmReportDetailActivity.this);
                        handleException(pmReportDetailResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
    }

    @Override
    public void onChangeListener(int status) {
//        super.onChangeListener(status);
        if (status == 404) {
            // 离线状态
            binding.rlOffLine.setVisibility(View.VISIBLE);
            binding.llShowDetail.setVisibility(View.GONE);
        } else {
            //去获取详情
            viewModel.getCardData(replaceCardId);
            binding.rlOffLine.setVisibility(View.GONE);
            binding.llShowDetail.setVisibility(View.VISIBLE);
        }
    }

    private void initView() {
        initTimePicker();
        binding.changeModel.setOnClickListener(this);
        binding.remark.addTextChangedListener(new MyTextWatcher(binding.tvLimit,binding.remark,50,PmReportDetailActivity.this));
        binding.materialTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.materialTitle.titleBackTv.setText("");
        binding.materialTitle.titleBackLl.setOnClickListener(this);
        binding.materialTitle.titleMenuConfirm.setText("提交");

        binding.tvEdit.setOnClickListener(this);
        binding.tvRemark.setOnClickListener(this);
        if (state != 3) {
            binding.materialTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
            binding.calender.setVisibility(View.VISIBLE);
            binding.llSelectDate.setOnClickListener(this);
        } else {
            binding.materialTitle.titleMenuConfirm.setVisibility(View.GONE);
            binding.calender.setVisibility(View.GONE);
            binding.tvEdit.setVisibility(View.GONE);
        }
        binding.materialTitle.titleMenuConfirm.setOnClickListener(this);
        binding.editEleSafe.setOnClickListener(this);
        binding.editLookCheck.setOnClickListener(this);
        binding.editFunctionCheck.setOnClickListener(this);



        //有网就显示详情,没网就不显示
        if (NetWorkUtils.getNetWorkState(PmReportDetailActivity.this) == 404) {
            binding.rlOffLine.setVisibility(View.VISIBLE);
            binding.llShowDetail.setVisibility(View.GONE);
        } else {
            viewModel.getCardData(replaceCardId);
            binding.rlOffLine.setVisibility(View.GONE);
            binding.llShowDetail.setVisibility(View.VISIBLE);
            //请求接口访问详情
        }
        if (state == 1) {
            binding.materialTitle.titleTextTv.setText("新增报告详情");
            binding.time.setText(getCurrentTime());

            //状态栏隐藏
            binding.rlState.setVisibility(View.GONE);
            binding.editEleSafe.setText("添加");
            binding.editLookCheck.setText("添加");
            binding.editFunctionCheck.setText("添加");
            binding.tvRemark.setVisibility(View.VISIBLE);
            binding.tvRemark.setText("添加");
            if (null !=userInfo && !TextUtils.isEmpty(userInfo.getStaffName())) {
                binding.tvUser.setText(userInfo.getStaffName());
            }
        } else {
            binding.materialTitle.titleTextTv.setText("查看报告详情");
            if (!TextUtils.isEmpty(detail.getPmReportVO().getCheckResultName())) {
                binding.satae.setText(detail.getPmReportVO().getCheckResultName());
                if (detail.getPmReportVO().getCheckResultName().equals("正常")) {
                    binding.satae.setBackground(getResources().getDrawable(R.drawable.corners_bg_75ca5c));
                } else {
                    binding.satae.setBackground(getResources().getDrawable(R.drawable.corners_bg_fb6769));
                }

            }
            //编辑页面  取科室
            if (!TextUtils.isEmpty(detail.getPmReportVO().getCardDeptName()) && !detail.getPmReportVO().getCardDeptName().equals("无")) {
                binding.taskRoom.setText(detail.getPmReportVO().getCardDeptName());
            }
            if (!TextUtils.isEmpty(detail.getPmReportVO().getPmDate())) {
                binding.time.setText(detail.getPmReportVO().getPmDate());
            }
            if (!TextUtils.isEmpty(detail.getPmReportVO().getPmUserName())) {
                binding.tvUser.setText(detail.getPmReportVO().getPmUserName());
            }
            if (null != detail) {
                if(!TextUtils.isEmpty(detail.getPmReportVO().getOffLineRemark())){
                    binding.remark.setText(detail.getPmReportVO().getOffLineRemark());
                    binding.remark.setSelection(detail.getPmReportVO().getOffLineRemark().length());

                    binding.offlineRemark.setText(detail.getPmReportVO().getOffLineRemark());
                    binding.remarkOff.setVisibility(View.VISIBLE);
                }
                for (PmReportDtl model : detail.getPmReportVO().getPmReportDtlList()) {
                    if(TextUtils.isEmpty(model.getCheckProjectName())){
                        continue;
                    }
                    switch (model.getCheckProjectName()) {
                        case "外观检测":
                            if (!TextUtils.isEmpty(model.getCheckResult())) {
                                binding.checkResultLook.setText(model.getCheckResult());
                            }
                            if (!TextUtils.isEmpty(model.getRemarks())) {
                                binding.proLook.setText(model.getRemarks());
                            }
                            if (!TextUtils.isEmpty(model.getCheckModelName())) {
                                binding.moduleLook.setText(model.getCheckModelName());
                            }
                            lookBack = model;
                            submit.addPmReportDtl(lookBack);
                            lookId = model.getId();
                            break;
                        case "电安全检测":
                            if (!TextUtils.isEmpty(model.getCheckResult())) {
                                binding.checkResultElect.setText(model.getCheckResult());
                            }
                            if (!TextUtils.isEmpty(model.getRemarks())) {
                                binding.proElect.setText(model.getRemarks());
                            }
                            if (!TextUtils.isEmpty(model.getCheckModelName())) {
                                binding.moduleElec.setText(model.getCheckModelName());
                            }
                            elecBack = model;
                            submit.addPmReportDtl(elecBack);
                            elecId = model.getId();
                            break;
                        case "性能检测":
                            if (!TextUtils.isEmpty(model.getCheckResult())) {
                                binding.checkResultFunction.setText(model.getCheckResult());
                            }
                            if (!TextUtils.isEmpty(model.getRemarks())) {
                                binding.proFunction.setText(model.getRemarks());
                            }
                            if (!TextUtils.isEmpty(model.getCheckModelName())) {
                                binding.moduleFunction.setText(model.getCheckModelName());
                            }
                            funtionBack = model;
                            submit.addPmReportDtl(funtionBack);
                            functionId = model.getId();
                            break;
                    }
                }
            }
            binding.rlState.setVisibility(View.VISIBLE);
            if (state == 2) {
                binding.editEleSafe.setText(null == elecBack || TextUtils.isEmpty(elecBack.getCheckResult()) ? "添加" : "编辑");
                binding.editLookCheck.setText(null == lookBack ||TextUtils.isEmpty(lookBack.getCheckResult()) ? "添加" : "编辑");
                binding.editFunctionCheck.setText(null == funtionBack ||TextUtils.isEmpty(funtionBack.getCheckResult()) ? "添加" : "编辑");
                binding.tvRemark.setText(null == detail || TextUtils.isEmpty(detail.getPmReportVO().getRemarks()) ? "添加":detail.getPmReportVO().getRemarks());
                binding.tvRemark.setTextColor( binding.tvRemark.getText().equals("添加")?getResources().getColor(R.color.C_369FF1):getResources().getColor(R.color.C_333333));
                binding.tvEdit.setVisibility( binding.tvRemark.getText().equals("添加")?View.GONE:View.VISIBLE);
                binding.tvState.setText("未确认");
                binding.tvState.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.unconfirmed, 0, 0, 0);
                binding.rlState.setBackgroundColor(getResources().getColor(R.color.C_FFFAF2));
            } else  if (state == 3){
                binding.tvRemark.setText(null == detail || TextUtils.isEmpty(detail.getPmReportVO().getRemarks()) || detail.getPmReportVO().getRemarks().equals("添加") ? "无":detail.getPmReportVO().getRemarks());
                binding.tvRemark.setTextColor(getResources().getColor(R.color.C_333333));
                binding.tvRemark.setOnClickListener(null);
                binding.tvEdit.setOnClickListener(null);
                binding.tvEdit.setVisibility(View.GONE);

                binding.editEleSafe.setText(null == elecBack ||TextUtils.isEmpty(elecBack.getCheckResult()) ? "无" : "点击查看");
                binding.editEleSafe.setOnClickListener(null == elecBack ||TextUtils.isEmpty(elecBack.getCheckResult()) ? null : this);
                if(binding.editEleSafe.getText().equals("无")){
                    binding.editEleSafe.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
                    binding.editEleSafe.setTextColor(getResources().getColor(R.color.C_999999));
                }

                binding.editLookCheck.setText(null == lookBack ||TextUtils.isEmpty(lookBack.getCheckResult()) ? "无" : "点击查看");
                binding.editLookCheck.setOnClickListener(null == lookBack ||TextUtils.isEmpty(lookBack.getCheckResult()) ? null : this);
                if(binding.editLookCheck.getText().equals("无")){
                    binding.editLookCheck.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
                    binding.editLookCheck.setTextColor(getResources().getColor(R.color.C_999999));
                }

                binding.editFunctionCheck.setText(null == funtionBack ||TextUtils.isEmpty(funtionBack.getCheckResult()) ? "无" : "点击查看");
                binding.editFunctionCheck.setOnClickListener(null == funtionBack ||TextUtils.isEmpty(funtionBack.getCheckResult()) ? null : this);
                if(binding.editFunctionCheck.getText().equals("无")){
                    binding.editFunctionCheck.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
                    binding.editFunctionCheck.setTextColor(getResources().getColor(R.color.C_999999));
                }
                binding.changeModel.setVisibility(View.GONE);
                binding.tvState.setText("已确认");
                binding.rlState.setBackgroundColor(getResources().getColor(R.color.C_ECFBFB));
                binding.tvState.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.right, 0, 0, 0);
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edit_ele_safe:
                if (null != elecBack &&null == elecBack.getPrjList() && state != 1 && !TextUtils.isEmpty(elecId)) {
                    viewModel.getPmProject(elecId, ELECT_SAFE);
                    return;
                }
                if(binding.editEleSafe.getText().equals("添加")){
                    state = 1;
                }
                if (null != elecBack && state != 3&& null!=elecBack.getPrjList() && elecBack.getPrjList().size()>0) {
                    state = 2;
                }
                ElectSafeActivity.launch(PmReportDetailActivity.this, state, replaceCardId, res, elecBack);
                break;
            case R.id.edit_look_check:
                //如果状态不是新增  并且是第一次跳转过去，之后返回回来就以修改后得数据为准，因为它还没提交
                if (null != lookBack &&null == lookBack.getPrjList() && state != 1 && !TextUtils.isEmpty(lookId)) {
                    viewModel.getPmProject(lookId, LOOKCHECK);
                    return;
                }
                if(binding.editLookCheck.getText().equals("添加")){
                    state = 1;
                }
                if (null != lookBack && state != 3 && null!=lookBack.getPrjList() && lookBack.getPrjList().size()>0) {
                    state = 2;
                }
                LookCheckActivity.launch(PmReportDetailActivity.this, state, replaceCardId, res, lookBack);
                break;
            case R.id.edit_function_check:
                if (!binding.moduleFunction.getText().toString().equals("无")) {
                    if (null != funtionBack &&null == funtionBack.getPrjList() && state != 1 && !TextUtils.isEmpty(functionId)) {
                        viewModel.getPmProject(functionId, FUNCTION);
                        return;
                    }
                    if(binding.editFunctionCheck.getText().equals("添加")){
                        state = 1;
                    }
                    if (null != funtionBack && state != 3&& null!=funtionBack.getPrjList() && funtionBack.getPrjList().size()>0) {
                        state = 2;
                    }
                    FunctionCheckActivity.launch(PmReportDetailActivity.this, state, replaceCardId, res, funtionBack, binding.moduleFunction.getText().toString());
                } else {
                    if(null != res && res.getPmFunModelName().equals("无")){
                        MyToast.makeText(PmReportDetailActivity.this, "该设备无性能检测模板,无法添加", MyToast.LENGTH_SHORT).show();
                        return;
                    }
                    MyToast.makeText(PmReportDetailActivity.this, "请选择模板后进行编辑", MyToast.LENGTH_SHORT).show();
                }
                break;
            case R.id.change_model:
                if(binding.moduleFunction.getText().toString().equals("无")){
                    typePosition = 0;
                }else{
                    typePosition = 1;
                }
                typeOptionsPickerView = PickerViewUtils.getOptionPickerView("", typeList, typePosition, PmReportDetailActivity.this, PickerViewUtils.getListener(binding.moduleFunction, typeList));
                typeOptionsPickerView.show();
                break;
            case R.id.title_menu_confirm:
                //判断日期
                if(TextUtils.isEmpty(binding.time.getText().toString())){
                    ToastUtil.toastWarning(PmReportDetailActivity.this,"请选择PM日期",-1);
                    return;
                }
                if( DateUtils.compareDate(binding.time.getText().toString(),DateUtils.getCurrFullDay())>0){
                    ToastUtil.toastWarning(PmReportDetailActivity.this,"PM日期不能晚于今日",-1);
                    return;
                }
                initPop();
                break;
            case R.id.ll_select_date:
                hideSoftInput();
                if (null != pvTime)
                    pvTime.show();
                break;
            case R.id.title_back_ll:
                onBackPressed();
                break;
            case R.id.tv_remark:
                if(binding.tvRemark.getText().equals("添加")){
                    RemarkActivity.launch(PmReportDetailActivity.this,"");
                }
                break;
            case R.id.tv_edit:
                RemarkActivity.launch(PmReportDetailActivity.this,binding.tvRemark.getText().toString());
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if(state != 3){
            noticeSave();
        }else {
            super.onBackPressed();
        }
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            if (null != mMenuBottom && mMenuBottom.isShowing()) {
                mMenuBottom.dismiss();
            }
            String look = binding.checkResultLook.getText().toString();
            String fun = binding.checkResultFunction.getText().toString();
            String elec = binding.checkResultElect.getText().toString();
            switch (v.getId()) {
                case R.id.sure_submit:
                    //仅保存
                   //保存到数据库
                    /** 1.检查数据库中是否存在本条数据
                     *  2.报告列表也要做判断
                     */

                    if (!TextUtils.isEmpty(look) || !TextUtils.isEmpty(fun) || !TextUtils.isEmpty(elec)) {
                        viewModel.check(save(),isReplace,cardId);
                    }else{
                      ToastUtil.toastWarning(PmReportDetailActivity.this,"请添加检测信息后再保存",-1);
                    }
                    break;
                case R.id.sure_other:
                    //提交
                    /** 1.检查数据库中是否存在本条数据
                     *  2.报告列表也要做判断
                     */
                    if (!TextUtils.isEmpty(look) || !TextUtils.isEmpty(fun) || !TextUtils.isEmpty(elec)) {
                        submit();
                        viewModel.submitPmReport(submit, MenuHelper.getAuidS().get("zc_pm"));
                    }else{
                        ToastUtil.toastWarning(PmReportDetailActivity.this,"请添加检测信息后再保存",-1);
                    }
                    break;
            }
        }
    };

    public void initPop() {
        //实例化SelectPicPopupWindow
        if (null == mMenuBottom) {
            mMenuBottom = new BottomMenuPopupStock(PmReportDetailActivity.this, itemsOnClick, "", "PM报告");
            mMenuBottom.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AlphaManager.backgroundAlpha(1f, PmReportDetailActivity.this);
                    mMenuBottom.setVisibility();
                }
            });
        }
        //显示窗口
        mMenuBottom.showAtLocation(PmReportDetailActivity.this.findViewById(R.id.ll_show_detail), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        boolean mobileConnected = NetWorkUtils.isMobileConnected(PmReportDetailActivity.this);
        if(!mobileConnected){
            mMenuBottom.sureOther.setVisibility(View.GONE);
        }
        if(!isLocalSave && state != 1){
            //如果不是新增或者 本地的数据，隐藏掉仅保存按钮
            mMenuBottom.sureSubmit.setVisibility(View.GONE);
        }
        AlphaManager.backgroundAlpha(0.7f, PmReportDetailActivity.this);
    }

    private void initTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2000, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(3000, 11, 31);
        //时间选择器
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                /*btn_Time.setText(getTime(date));*/
                binding.time.setText(getTime(date));
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                pvTime.setDate(cal);

            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .isCenterLabel(true)
                .isCyclic(true)
                .setDividerColor(0xFFDCDCDC)
                .setContentSize(13)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setTextColorCenter(0xFF369FF1)
                .setTextColorOut(0xFF666666)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();

    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private String getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(state != 3){
            openBroadCast();
        }
        if(NetWorkUtils.isMobileConnected(PmReportDetailActivity.this)){
            viewModel.getCardData(replaceCardId);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(state != 3){
            closeBroadCast();
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Constants.RESULT_OK) {
            switch (requestCode) {
                case ELECT_SAFE:
                    elecBack = (PmReportDtl) data.getSerializableExtra("ElecCheckResult");
                    binding.checkResultElect.setText(elecBack.getCheckResult());
                    if (!TextUtils.isEmpty(elecBack.getRemarks())) {
                        binding.proElect.setText(elecBack.getRemarks());
                    }
                    binding.editEleSafe.setText("编辑");
                    submit.addPmReportDtl(elecBack);
                    break;
                case FUNCTION:
                    funtionBack = (PmReportDtl) data.getSerializableExtra("FunctionCheckResult");
                    binding.checkResultFunction.setText(funtionBack.getCheckResult());
                    if (!TextUtils.isEmpty(funtionBack.getRemarks())) {
                        binding.proFunction.setText(funtionBack.getRemarks());
                    }
                    binding.editFunctionCheck.setText("编辑");
                    submit.addPmReportDtl(funtionBack);
                    break;
                case LOOKCHECK:
                    //更新界面 结果  加提交数据
                    lookBack = (PmReportDtl) data.getSerializableExtra("LookCheckResult");
                    binding.checkResultLook.setText(lookBack.getCheckResult());
                    if (!TextUtils.isEmpty(lookBack.getRemarks())) {
                        binding.proLook.setText(lookBack.getRemarks());
                    }
                    binding.editLookCheck.setText("编辑");
                    submit.addPmReportDtl(lookBack);
                    break;
                case REMARK:
                    String remark = data.getStringExtra("remark");
                    if(!TextUtils.isEmpty(remark)){
                        binding.tvRemark.setText(remark);
                        binding.tvRemark.setTextColor(getResources().getColor(R.color.C_333333));
                        binding.tvEdit.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        }
        if(state != 3){
            checkPmResult();
        }
    }
    /**
     * 设置PM 结果状态
     */
    public void checkPmResult() {
        String look = binding.checkResultLook.getText().toString();
        String fun = binding.checkResultFunction.getText().toString();
        String elec = binding.checkResultElect.getText().toString();

        if (!TextUtils.isEmpty(look) || !TextUtils.isEmpty(fun) || !TextUtils.isEmpty(elec)) {
            if(!TextUtils.isEmpty(look) && !look.equals("合格")){
                binding.satae.setText("故障");
                binding.satae.setBackground(getResources().getDrawable(R.drawable.corners_bg_fb6769));
            }
            if(!TextUtils.isEmpty(look) && look.equals("合格")){
                binding.satae.setBackground(getResources().getDrawable(R.drawable.corners_bg_75ca5c));
                binding.satae.setText("正常");
            }
            if(!TextUtils.isEmpty(fun) && !fun.equals("合格")){
                binding.satae.setText("故障");
                binding.satae.setBackground(getResources().getDrawable(R.drawable.corners_bg_fb6769));
            }
            if(!TextUtils.isEmpty(fun) && fun.equals("合格")){
                binding.satae.setBackground(getResources().getDrawable(R.drawable.corners_bg_75ca5c));
                binding.satae.setText("正常");
            }
            if(!TextUtils.isEmpty(elec) && !elec.equals("合格")){
                binding.satae.setText("故障");
                binding.satae.setBackground(getResources().getDrawable(R.drawable.corners_bg_fb6769));
            }
            if(!TextUtils.isEmpty(elec) && elec.equals("合格")){
                binding.satae.setBackground(getResources().getDrawable(R.drawable.corners_bg_75ca5c));
                binding.satae.setText("正常");
            }
            binding.satae.setVisibility(View.VISIBLE);
        } else {
            binding.satae.setVisibility(View.GONE);
        }
    }

    //提交表单到服务器
    public void submit() {

        // 新增的时候  应后端要求  提交的时候  就算没有填模板  也要添加数据
        if(state != 3){
            if(binding.editLookCheck.getText().toString().equals("添加")){
                PmReportDtl pmReportDtl = new PmReportDtl();
                pmReportDtl.setCheckModel("默认模板");
                pmReportDtl.setCheckProject("85-1");
                if(!TextUtils.isEmpty(lookId)){
                    pmReportDtl.setId(lookId);
                }
                pmReportDtl.setCheckProjectName("外观检测");
                submit.addPmReportDtl(pmReportDtl);
            }
            if(binding.editEleSafe.getText().toString().equals("添加")){
                PmReportDtl pmReportDtl = new PmReportDtl();
                pmReportDtl.setCheckModel("默认模板");
                pmReportDtl.setCheckProjectName("电安全检测");
                pmReportDtl.setCheckProject("85-2");
                if(!TextUtils.isEmpty(elecId)){
                    pmReportDtl.setId(elecId);
                }
                submit.addPmReportDtl(pmReportDtl);
            }
            if(binding.editFunctionCheck.getText().toString().equals("添加") || binding.editFunctionCheck.getText().toString().equals("无")){
                PmReportDtl pmReportDtl = new PmReportDtl();
                if(!binding.moduleFunction.getText().toString().equals("无")){
                    pmReportDtl.setCheckModel(binding.moduleFunction.getText().toString());
                }else{
                    pmReportDtl.setCheckModel("无");
                }
                pmReportDtl.setCheckProjectName("性能检测");
                pmReportDtl.setCheckProject("85-3");
                if(!TextUtils.isEmpty(functionId)){
                    pmReportDtl.setId(functionId);
                }
                submit.addPmReportDtl(pmReportDtl);
            }
        }


        if(null!= detail && !TextUtils.isEmpty(detail.getPmReportVO().getId())) {
            submit.setId(detail.getPmReportVO().getId());
        }
        if(null!= res && !TextUtils.isEmpty(res.getId())){
            submit.setCardId(res.getId());
        }else{
            ToastUtil.toastWarning(PmReportDetailActivity.this,"卡片ID无法获取，请联系管理员",-1);
            return;
        }
        submit.setQrCodeOld(cardId);
        submit.setQrCodeNew(replaceCardId);
        if (!TextUtils.isEmpty(binding.time.getText().toString())) {
            submit.setPmDate(binding.time.getText().toString());
        }
        if (!TextUtils.isEmpty(binding.tvRemark.getText().toString())&& !binding.tvRemark.getText().toString().equals("添加")) {
            submit.setRemarks(binding.tvRemark.getText().toString());
        }
        if (MenuHelper.getAuidS().containsKey("zc_pm")) {
            submit.setPmUserId(MenuHelper.getAuidS().get("zc_pm"));
            submit.setCreateUserId(MenuHelper.getAuidS().get("zc_pm"));
        }
        if (!TextUtils.isEmpty(binding.satae.getText().toString())) {
            if("正常".equals(binding.satae.getText().toString())){
                submit.setCheckResult("84-1");
            }else {  //if("不合格".equals(binding.satae.getText().toString()))
                submit.setCheckResult("84-2");
            }
        }
        // 设置模板-----------------    电安全和外观暂时不设置
        if(!binding.moduleFunction.getText().toString().equals("无")){
            submit.setCheckModule("性能检测",binding.moduleFunction.getText().toString());
        }

        submit.setCreateDatetime(DateUtils.getCurrFullDay());
    }

    /**
     * 存储到本地数据库
     */
    public PmReportDetailResponse save(){
        localDetail = new PmReportDetailResponse();
        PmReportDetailResponse.PmReportVO reportVO =new PmReportDetailResponse.PmReportVO();
        reportVO.setQrCode(replaceCardId);
        reportVO.setPmDate(binding.time.getText().toString());
        if (!TextUtils.isEmpty(binding.satae.getText().toString())) {
            if("正常".equals(binding.satae.getText().toString())){
                reportVO.setCheckResult("84-1");
                reportVO.setCheckResultName("正常");
            }else if("故障".equals(binding.satae.getText().toString())){
                reportVO.setCheckResult("84-2");
                reportVO.setCheckResultName("故障");
            }
        }
        if (!TextUtils.isEmpty(binding.tvUser.getText().toString())){
            reportVO.setPmUserName(binding.tvUser.getText().toString());
        }
        if (!TextUtils.isEmpty(binding.remark.getText().toString())){
            reportVO.setOffLineRemark(binding.remark.getText().toString());
        }
        if (!TextUtils.isEmpty(binding.tvRemark.getText().toString()) && !binding.tvRemark.getText().toString().equals("添加")){
            reportVO.setRemarks(binding.tvRemark.getText().toString());
        }
        if (null != res && !TextUtils.isEmpty(res.getCardName())){
            reportVO.setCardName(res.getCardName());
        }
        if (null != res && !TextUtils.isEmpty(res.getDepartmentName())){
            reportVO.setCardDeptName(res.getDepartmentName());
        }
        List<PmReportDtl> pmReportDtlList = new ArrayList<>();
        if(null != lookBack){
            pmReportDtlList.add(lookBack);
        }
       if(null != elecBack){
           pmReportDtlList.add(elecBack);
       }
        if(null != funtionBack){
            pmReportDtlList.add(funtionBack);
        }
        reportVO.setPmReportDtlList(pmReportDtlList);
        localDetail.setPmReportVO(reportVO);
        return localDetail;
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        //判断是否符合 医院二维码规则
        if(!MD5Util.IsUUID(msg)){
            ToastUtil.toastWarning(context,getString(R.string.notBelong),-1);
            return;
        }
        //再判断是否属于当前范围

        //再判断是否和当前得QRcode一致
        if( !msg .equals(replaceCardId)){
            replaceCardId = msg;
            noticeReplace(replaceCardId);
        }else{
            ToastUtil.toastWarning(context,"和当前卡片一致，请确认",-1);
        }


    }
    private CommonDialog noticeReplaceDialog;
    public void noticeReplace(String scan_Code) {
        noticeReplaceDialog = new CommonDialog.Builder()
                .setTitle("提醒")
                .setContent("是否需要更换成当前扫码的设备？")
                .setCancelBtn("否", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeReplaceDialog.dismiss();
                    }
                })
                .setConfirmBtn("是", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeReplaceDialog.dismiss();
                        isReplace = true;
                        if(NetWorkUtils.isMobileConnected(PmReportDetailActivity.this)){
                            viewModel.getCardData(scan_Code);
                        }
                    }
                })
                .create();
        noticeReplaceDialog.show(getSupportFragmentManager(), null);
    }
    private CommonDialog noticeSaveDialog;
    public void noticeSave() {
        noticeSaveDialog = new CommonDialog.Builder()
                .setTitle("提醒")
                .setContent("是否未保存就退出？")
                .setCancelBtn("否", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeSaveDialog.dismiss();
                    }
                })
                .setConfirmBtn("是", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeSaveDialog.dismiss();
                        finish();
                    }
                })
                .create();
        noticeSaveDialog.show(getSupportFragmentManager(), null);
    }
}
